package com.vint.lintcode;

import com.vint.common.ListNode;

/**
 * 数位相加，链表， 315,592= 808
 */
public class Lintcode167 {
	public ListNode addLists(ListNode l1, ListNode l2) {
		if (null == l1) {
			return l2;
		}
		if (null == l2) {
			return l1;
		}

		ListNode head = l1;
		int a = l1.val;
		head.val = (a + l2.val) % 10;
		int carry  = (a + l2.val) / 10;
		ListNode headA = l1.next;
		ListNode preA = l1;
		ListNode headB = l2.next;
		ListNode preB = l2;
		while (null != headA && null != headB) {
			preA = headA;
			preB = headB;
			int t = preA.val;
			preA.val = (t + preB.val + carry )%10;
			carry = (t + preB.val + carry ) / 10;
			headA = headA.next;
			headB = headB.next;
		}
		if (null == headA) {
			preA.next = headB;
			while (null != headB) {
				preA = headB;
				int t = preA.val;
				preA.val = (preA.val + carry) % 10;
				carry = (t + carry) / 10;
				headB = headB.next;
			}
		} else {
			while (null != headA) {
				preA = headA;
				int t = preA.val;
				preA.val = (preA.val + carry) % 10;
				carry = (t + carry) / 10;
				headA = headA.next;
			}
		}
		if(carry !=0){
			preA.next = new ListNode(carry);
		}

		return head;

	}
	public static void main(String[] args) {
		Lintcode167 lintcode167 = new Lintcode167();
		ListNode l1 = new ListNode(3);
		l1.next = new ListNode(1);
		l1.next.next = new ListNode(5);
		ListNode l2 = new ListNode(5);
		l2.next = new ListNode(9);
		l2.next.next = new ListNode(2);
		lintcode167.addLists(l1,l2);
		System.out.println("hello");
	}

}
